import { FormEvent } from "react";

import { useAuth } from "content/auth-content";
import { useAsync } from "utils/hooks/use-async";

export const RegisterPage = ({ onError }: { onError: (error: Error | null) => void }) => {
  const { run } = useAsync(undefined, { throwOnError: true });
  const { register } = useAuth();
  const handSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const username = (e.currentTarget.elements[0] as HTMLInputElement).value;
    const password = (e.currentTarget.elements[1] as HTMLInputElement).value;
    try {
      await run(register({ username, password }));
    } catch (error) {
      onError((error as Error));
    }
  }

  return (
    <div className="register-container">
      <form action="#" onSubmit={handSubmit}>
        <div>
          <label htmlFor="">用户名</label>
          <input type="text" id="username" />
        </div>
        <div>
          <label htmlFor="">密码</label>
          <input type="password" id="password" />
        </div>
        <button type="submit">注册</button>
      </form>
    </div>
  );
}